<template>
  <el-select
    v-model="selectedVal"
    :style="{width:width}"
    filterable
    remote
    reserve-keyword
    :placeholder="placeholder"
    clearable
    :remote-method="remoteMethod">
    <el-option
      v-for="item in options"
      :key="item.id"
      :label="item.value"
      :value="item.value" />
  </el-select>
</template>
<script>
export default {
  props: {
    value: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: '请输入邮箱'
    },
    width: {
      type: String,
      default: '100%'
    }
  },
  data() {
    return {
      emailSuffix: ['@qq.com', '@163.com', '@126.com', '@yahoo.cn', '@sina.com', '@shouhu.com', '@outlook.com', '@gmail.com'],
      selectedVal: '',
      options: []
    }
  },
  watch: {
    value: function(val) {
      this.remoteMethod(val)
      setTimeout(() => {
        this.selectedVal = val
      }, 200)
    },
    selectedVal: function(val) {
      this.$emit('input', val)
    }
  },
  mounted() {
  },
  created() {
    this.options = []
    this.remoteMethod(this.value)
    this.selectedVal = this.value
  },
  methods: {
    remoteMethod(query) {
      if (query) {
        setTimeout(() => {
          this.options = []
          if (query.indexOf('@') > -1) {
            var newSuffix = this.emailSuffix.filter(item => {
              return item.toLowerCase().indexOf(query.substring(query.indexOf('@'))) > -1
            })
            if (newSuffix.length === 0) {
              this.options.push({
                id: query,
                value: query
              })
            } else {
              newSuffix.forEach(item => {
                this.options.push({
                  id: query.substring(0, query.indexOf('@')) + item,
                  value: query.substring(0, query.indexOf('@')) + item
                })
              })
            }
          } else {
            var results = []
            this.emailSuffix.forEach(item => {
              results.push({
                id: query + item,
                value: query + item
              })
            })
            this.options = results
          }
        }, 100)
      } else {
        this.options = []
      }
    }
  }
}
</script>
<style lang="scss">
</style>

